﻿using System.Collections.Generic;
using Entitas;
using System.Linq;
class EnemyRoamingMovementCommandSystem : ReactiveSystem<RequestEntity>, ICleanupSystem
{
    CommandContext commandContext;
    EnemyContext enemyContext;
    RequestContext requestContext;
    public EnemyRoamingMovementCommandSystem(Contexts contexts) : base(contexts.request)
    {
        commandContext = contexts.command;
        enemyContext = contexts.enemy;
        requestContext = contexts.request;
    }



    protected override void Execute(List<RequestEntity> entities)
    {
        foreach (var e in entities)
        {
            var enemy = enemyContext.GetEntityWithName(e.roamingMovementRequest.Owner);
            if (ServiceManager.PhysicsService.CastRayToCollider(enemy,enemy.position.value, e.roamingMovementRequest.direction) == false)
            {
                ServiceManager.DebugMessageService.Print("enemy is Able to move here");
                commandContext.CreateEntity().AddRoamingMovementCommand(e.roamingMovementRequest.Owner, e.roamingMovementRequest.direction);
            }
            else ServiceManager.DebugMessageService.Print("enemy cannot move here");
        }
    }

    protected override bool Filter(RequestEntity entity)
    {
        return entity.hasRoamingMovementRequest;
    }

    protected override ICollector<RequestEntity> GetTrigger(IContext<RequestEntity> context)
    {
        return context.CreateCollector(RequestMatcher.RoamingMovementRequest.Added());
    }

    public void Cleanup()
    {
        foreach (var e in requestContext.GetEntities().Where(x => x.hasRoamingMovementRequest))
        {
            e.Destroy();
        }
    }
}

